package com.vision.util.http.util;

import com.vision.util.http.AbsHttpFactory;
import com.vision.util.http.AbsRequestDeal;
import com.vision.util.http.param.GetParams;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Map;

/**
 * @author zhongchao
 * @title
 * @date 2017-08-22
 * @since v1.0.0
 */
public class HttpRequestDao2<T> {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestDao2.class);

    private CloseableHttpClient httpClient;

    private RequestConfig requestConfig;

    private HttpClientContext httpClientContext;

    private String charset = "UTF-8";

    private Map<String, String> headers;

    private Map<String, String> params;

    public HttpRequestDao2(AbsHttpFactory factory) {
        Assert.notNull(factory);
        this.httpClient = factory.getHttpClient();
        this.requestConfig = factory.getRequestConfig();
        this.httpClientContext = HttpClientContext.create();
    }

    public HttpRequestDao2 init(String charset, Map<String, String> headers, Map<String, String> params) {
        this.charset = charset;
        this.headers = headers;
        this.params = params;
        return this;
    }

    public T get(String url, AbsRequestDeal<T> requestDeal) {
        T t = null;
        try {
            HttpRequestBase request = new GetParams(url, charset).setHeaders(headers).setParams(params).build();
            CloseableHttpResponse response = httpClient.execute(request, httpClientContext);
            requestDeal.onSuccess(response);
            t = requestDeal.getResopnse();
        } catch (IOException e) {
            requestDeal.onException(url, e);
        }
        return t;
    }

    public T post(String url, AbsRequestDeal<T> requestDeal) {
        T t = null;
        try {
            HttpRequestBase request = new GetParams(url, charset).setHeaders(headers).setParams(params).build();
            CloseableHttpResponse response = httpClient.execute(request, httpClientContext);
            requestDeal.onSuccess(response);
            t = requestDeal.getResopnse();
        } catch (IOException e) {
            requestDeal.onException(url, e);
        }
        return t;
    }


    public HttpClientContext getHttpClientContext() {
        return httpClientContext;
    }
}
